<template>
  <div class="platform-statistics">
    <!-- 统计标题栏 -->
    <div class="statistics-header">
      <h3>平台统计</h3>
      <el-button type="primary" plain size="small" @click="handleRefresh">
        <el-icon><Refresh /></el-icon> 刷新
      </el-button>
    </div>
    
    <!-- 数据加载中 -->
    <div v-if="loading" class="loading-container">
      <el-skeleton :rows="5" animated />
    </div>
    
    <!-- 统计卡片区域 -->
    <div v-else class="statistics-content">
      <!-- 概览数据卡片 -->
      <div class="stats-overview">
        <el-card class="stats-card" v-for="(value, key) in overviewStats" :key="key">
          <template #header>
            <div class="card-header">{{ getStatLabel(key) }}</div>
          </template>
          <div class="card-value">{{ value || 0 }}</div>
        </el-card>
      </div>
      
      <!-- 内容质量分析 -->
      <el-card class="quality-card">
        <template #header>
          <div class="card-header">内容质量分析</div>
        </template>
        <div class="quality-content" v-if="qualityStats">
          <div class="quality-item" v-for="(value, key) in qualityStats" :key="key">
            <span class="quality-label">{{ getQualityLabel(key) }}</span>
            <el-progress 
              :percentage="value" 
              :status="getQualityStatus(key, value)" 
              :color="getQualityColor(key, value)"
            />
          </div>
        </div>
      </el-card>
      
      <!-- 内容分布 -->
      <el-card class="distribution-card">
        <template #header>
          <div class="card-header">内容分布</div>
        </template>
        <div class="distribution-content" v-if="distributionStats">
          <!-- 问题状态分布 -->
          <div class="distribution-section">
            <h4>问题状态分布</h4>
            <div class="distribution-chart">
              <div 
                v-for="(item, index) in questionStatusItems" 
                :key="index"
                class="distribution-bar"
                :style="{ 
                  width: `${item.percentage}%`, 
                  backgroundColor: item.color
                }"
              ></div>
            </div>
            <div class="distribution-legend">
              <div 
                v-for="(item, index) in questionStatusItems" 
                :key="index"
                class="legend-item"
              >
                <span 
                  class="legend-color" 
                  :style="{ backgroundColor: item.color }"
                ></span>
                <span class="legend-label">{{ item.label }}: {{ item.value }}个 ({{ item.percentage }}%)</span>
              </div>
            </div>
          </div>
          
          <!-- 用户角色分布 -->
          <div class="distribution-section">
            <h4>用户角色分布</h4>
            <div class="distribution-chart">
              <div 
                v-for="(item, index) in userRoleItems" 
                :key="index"
                class="distribution-bar"
                :style="{ 
                  width: `${item.percentage}%`, 
                  backgroundColor: item.color
                }"
              ></div>
            </div>
            <div class="distribution-legend">
              <div 
                v-for="(item, index) in userRoleItems" 
                :key="index"
                class="legend-item"
              >
                <span 
                  class="legend-color" 
                  :style="{ backgroundColor: item.color }"
                ></span>
                <span class="legend-label">{{ item.label }}: {{ item.value }}人 ({{ item.percentage }}%)</span>
              </div>
            </div>
          </div>
        </div>
      </el-card>
      
      <!-- 敏感内容统计 -->
      <el-card class="sensitive-card" v-if="sensitiveStats">
        <template #header>
          <div class="card-header">敏感内容监控</div>
        </template>
        <div class="sensitive-content">
          <el-alert
            v-if="sensitiveStats.recentDetections > 0"
            type="warning"
            :title="`最近24小时内检测到 ${sensitiveStats.recentDetections} 条敏感内容`"
            show-icon
          />
          <el-alert
            v-else
            type="success"
            title="最近24小时内未检测到敏感内容"
            show-icon
          />
          
          <div class="sensitive-stats">
            <div class="sensitive-item">
              <div class="sensitive-label">总检测次数</div>
              <div class="sensitive-value">{{ sensitiveStats.totalDetections || 0 }}</div>
            </div>
            <div class="sensitive-item">
              <div class="sensitive-label">敏感词库数量</div>
              <div class="sensitive-value">{{ sensitiveStats.sensitiveWordsCount || 0 }}</div>
            </div>
            <div class="sensitive-item">
              <div class="sensitive-label">拦截率</div>
              <div class="sensitive-value">{{ sensitiveStats.blockRate || 0 }}%</div>
            </div>
          </div>
        </div>
      </el-card>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import { Refresh } from '@element-plus/icons-vue';
import { 
  getPlatformStatistics, 
  getContentQualityStatistics,
  getSensitiveContentStatistics 
} from '../../api/admin';

// 属性和事件
const props = defineProps({});
const emit = defineEmits(['refresh']);

// 数据状态
const loading = ref(false);
const stats = ref(null);
const qualityStats = ref(null);
const sensitiveStats = ref(null);

// 加载所有统计数据
const loadStatistics = async () => {
  try {
    loading.value = true;
    
    // 加载平台概览数据
    const platformRes = await getPlatformStatistics();
    if (platformRes.code === 200) {
      stats.value = platformRes.data;
    } else {
      ElMessage.warning('加载平台统计数据失败');
    }
    
    // 加载内容质量数据
    const qualityRes = await getContentQualityStatistics();
    if (qualityRes.code === 200) {
      qualityStats.value = qualityRes.data.qualityMetrics;
    }
    
    // 加载敏感内容统计
    const sensitiveRes = await getSensitiveContentStatistics();
    if (sensitiveRes.code === 200) {
      sensitiveStats.value = sensitiveRes.data;
    }
  } catch (error) {
    console.error('加载统计数据失败:', error);
    ElMessage.error('加载统计数据失败');
  } finally {
    loading.value = false;
  }
};

// 刷新统计数据
const handleRefresh = () => {
  loadStatistics();
  emit('refresh');
};

// 计算属性：概览统计指标
const overviewStats = computed(() => {
  if (!stats.value) return {};
  
  return {
    totalUsers: stats.value.totalUsers,
    totalQuestions: stats.value.totalQuestions,
    totalAnswers: stats.value.totalAnswers,
    totalComments: stats.value.totalComments,
    totalViews: stats.value.totalViews,
    dailyActiveUsers: stats.value.dailyActiveUsers
  };
});

// 计算属性：内容分布统计
const distributionStats = computed(() => {
  if (!stats.value) return null;
  return stats.value.distribution;
});

// 计算属性：问题状态分布项
const questionStatusItems = computed(() => {
  if (!distributionStats.value || !distributionStats.value.questionStatus) {
    return [];
  }
  
  const statusData = distributionStats.value.questionStatus;
  const total = Object.values(statusData).reduce((sum, val) => sum + val, 0);
  
  const statusMap = {
    pending: { label: '待审核', color: '#E6A23C' },
    published: { label: '已发布', color: '#409EFF' },
    resolved: { label: '已解决', color: '#67C23A' },
    closed: { label: '已关闭', color: '#909399' },
    rejected: { label: '已拒绝', color: '#F56C6C' }
  };
  
  return Object.entries(statusData).map(([key, value]) => ({
    label: statusMap[key]?.label || key,
    value: value,
    percentage: total > 0 ? Math.round((value / total) * 100) : 0,
    color: statusMap[key]?.color || '#409EFF'
  }));
});

// 计算属性：用户角色分布项
const userRoleItems = computed(() => {
  if (!distributionStats.value || !distributionStats.value.userRoles) {
    return [];
  }
  
  const roleData = distributionStats.value.userRoles;
  const total = Object.values(roleData).reduce((sum, val) => sum + val, 0);
  
  const roleMap = {
    normalUsers: { label: '普通用户', color: '#909399' },
    expertUsers: { label: '专家用户', color: '#67C23A' },
    adminUsers: { label: '管理员', color: '#F56C6C' }
  };
  
  return Object.entries(roleData).map(([key, value]) => ({
    label: roleMap[key]?.label || key,
    value: value,
    percentage: total > 0 ? Math.round((value / total) * 100) : 0,
    color: roleMap[key]?.color || '#409EFF'
  }));
});

// 辅助函数：获取统计指标标签
const getStatLabel = (key) => {
  const labelMap = {
    totalUsers: '总用户数',
    totalQuestions: '总问题数',
    totalAnswers: '总回答数',
    totalComments: '总评论数',
    totalViews: '总浏览量',
    dailyActiveUsers: '日活跃用户'
  };
  
  return labelMap[key] || key;
};

// 辅助函数：获取质量指标标签
const getQualityLabel = (key) => {
  const labelMap = {
    avgQuestionScore: '问题平均质量分',
    avgAnswerScore: '回答平均质量分',
    avgResponseTime: '平均响应时间(小时)',
    solvedRate: '问题解决率',
    contentCoverage: '内容覆盖率'
  };
  
  return labelMap[key] || key;
};

// 辅助函数：获取质量指标状态
const getQualityStatus = (key, value) => {
  if (key === 'avgResponseTime') {
    return value <= 24 ? 'success' : value <= 48 ? 'warning' : 'exception';
  }
  
  return value >= 70 ? 'success' : value >= 50 ? 'warning' : 'exception';
};

// 辅助函数：获取质量指标颜色
const getQualityColor = (key, value) => {
  if (key === 'avgResponseTime') {
    if (value <= 12) return '#67C23A';
    if (value <= 24) return '#67C23A';
    if (value <= 48) return '#E6A23C';
    return '#F56C6C';
  }
  
  if (value >= 80) return '#67C23A';
  if (value >= 70) return '#67C23A';
  if (value >= 50) return '#E6A23C';
  return '#F56C6C';
};

// 生命周期钩子
onMounted(() => {
  loadStatistics();
});
</script>

<style scoped>
/* 统计标题样式 */
.statistics-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.statistics-header h3 {
  margin: 0;
  color: #303133;
}

/* 加载中样式 */
.loading-container {
  padding: 20px;
}

/* 统计内容样式 */
.statistics-content {
  display: flex;
  flex-direction: column;
  gap: 24px;
}

/* 概览卡片样式 */
.stats-overview {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
  margin-bottom: 8px;
}

.stats-card {
  flex: 1;
  min-width: 180px;
}

.card-header {
  font-size: 16px;
  font-weight: 500;
}

.card-value {
  font-size: 32px;
  font-weight: 600;
  color: #409EFF;
  text-align: center;
  padding: 10px 0;
}

/* 质量分析样式 */
.quality-content {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.quality-item {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.quality-label {
  font-size: 14px;
  color: #606266;
}

/* 分布统计样式 */
.distribution-content {
  display: flex;
  flex-direction: column;
  gap: 24px;
}

.distribution-section h4 {
  margin-top: 0;
  margin-bottom: 16px;
  color: #606266;
}

.distribution-chart {
  height: 24px;
  display: flex;
  border-radius: 4px;
  overflow: hidden;
  margin-bottom: 12px;
}

.distribution-bar {
  height: 100%;
  transition: width 0.3s ease;
}

.distribution-legend {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
}

.legend-item {
  display: flex;
  align-items: center;
  gap: 8px;
}

.legend-color {
  width: 14px;
  height: 14px;
  border-radius: 2px;
}

.legend-label {
  font-size: 14px;
  color: #606266;
}

/* 敏感内容统计样式 */
.sensitive-content {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.sensitive-stats {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
  margin-top: 8px;
}

.sensitive-item {
  flex: 1;
  min-width: 120px;
  padding: 16px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.sensitive-label {
  font-size: 14px;
  color: #606266;
  margin-bottom: 8px;
}

.sensitive-value {
  font-size: 20px;
  font-weight: 600;
  color: #303133;
}
</style> 